package com.lis.scf.exception;


import com.lis.scf.common.dto.ResponseMessage;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandleAdvice {

    // 处理 DTO 层注解验证失败的异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseMessage handleValidationException(MethodArgumentNotValidException e) {
        // 获取第一个验证失败的消息（也可收集所有错误消息）
        String errorMsg = e.getBindingResult().getFieldError().getDefaultMessage();
        return new ResponseMessage(500, null, errorMsg);
    }

    // 处理自定义业务异常（如用户名重复）
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResponseMessage handleBusinessException(BusinessException e) {
        return new ResponseMessage(500, e.getMessage(), false);
    }



    // 处理其他未捕获的异常（可选）
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseMessage handleOtherException(Exception e) {
        return new ResponseMessage(500, "服务器内部错误：" + e.getMessage(), false);
    }





    //    Logger log = LoggerFactory.getLogger(GlobalExceptionHandleAdvice.class);
//    @ExceptionHandler(value = Exception.class)
//    public ResponseMessage handleException(Exception e, HttpServletRequest request, HttpServletResponse response) {
//        //记录日志
//
//
//
////        log.error("统一异常:",e);
//        return new ResponseMessage(500,"error",null);
//    }
}
